
import { TypePageFocus } from "../type";
export function getUUid() {
  return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
    var r = Math.random() * 16 | 0, v = c == 'x' ? r : (r & 0x3 | 0x8);
    return v.toString(16);
  });
}

export function getKeyValue(code: number, _keyboard: TypePageFocus.TypeKeys) {
  let _key: (keyof TypePageFocus.TypeKeys) | undefined = undefined
  for (const key in _keyboard) {
    const ele = _keyboard[key as keyof TypePageFocus.TypeKeys];
    if (ele === code) {
      _key = key as (keyof TypePageFocus.TypeKeys)
      continue
    }
  }
  return _key
}


/**
 * 判断某个元素是否在某个元素内
* 兼容不支持contains的浏览器
* @param parent 父元素
* @param child 子元素
*/
export function contains(parent: HTMLElement, child?: HTMLElement) {
  if (!parent || !child) return false
  if (parent === child) return true;
  if (parent.contains) return parent.contains(child);
  let node = child.parentNode;
  while (node !== null) {
    if (node === parent) return true;
    node = node.parentNode;
  }
  return false;
}


export function getBoundingClientRect(el: any) {
  if (!el) {
    return { left: 0, top: 0, width: 0, height: 0, right: 0, bottom: 0, x: 0, y: 0, centerX: 0, centerY: 0, }
  }
  const rect = el.getBoundingClientRect() || {};
  const scrollLeft = window.pageXOffset || document.documentElement.scrollLeft;
  const scrollTop = window.pageYOffset || document.documentElement.scrollTop;
  const clientLeft = document.documentElement.clientLeft || 0;
  const clientTop = document.documentElement.clientTop || 0;
  return {
    left: rect.left + scrollLeft - clientLeft,
    top: rect.top + scrollTop - clientTop,
    width: rect.width,
    height: rect.height,
    right: rect.right + scrollLeft - clientLeft,
    bottom: rect.bottom + scrollTop - clientTop,
    x: rect.x || rect.left,
    y: rect.y || rect.top,
    centerX: rect.width / 2 + rect.left,
    centerY: rect.height / 2 + rect.top,
    toJSON: rect.toJSON || (() => { }),
    ...(rect)
  }
}


/**获取元素是否在页面中 */
export function isInViewport(ele: HTMLElement) {
  if (!ele) return false
  const rect = getBoundingClientRect(ele);
  const isVisible = (rect.top < window.innerHeight || rect.left < window.innerWidth) && (rect.bottom > 0 || rect.right > 0);
  return isVisible
}